package br.org.isvi.interpretador.portugol.access;

import java.util.HashMap;
import java.util.List;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;

public abstract class AbstractDAO<T> {
	
	private static DataContext ctx = DataContext.createDataContext();
	
	public static DataContext getCtx() {
		return ctx;
	}
	
	public abstract Class<T> getType();
	
	public List<T> obterTodos() {
		SelectQuery query = new SelectQuery(getType());
		
		return getCtx().performQuery(query);
	}
	
	public T obterPorId(Integer id) {//TODO ALTERAR ISSO
		HashMap<String, Integer> params = new HashMap<String, Integer>();
		params.put("id", id);
		
		SelectQuery query = new SelectQuery(getType(), Expression.fromString("id = $id").expWithParameters(params));
		T ret = null;
		
		try { 
			ret = (T) getCtx().performQuery(query).get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ret;
	}
	
	public void persistir() {
		getCtx().commitChanges();
	}
	
	public T novo() {
		return (T) getCtx().newObject(getType());
	}
}
